﻿using Share;
using UnityEngine;
using UnityEngine.UI;

public class RotateSelf : MonoBehaviour
{
    [SerializeField]
    private float m_RotateSpeed; // 旋转速度

    [SerializeField]
    private float m_RotateAngle; // 当前旋转角度

    [SerializeField]
    private Sprite m_PlaySprite; // 播放状态的图标

    [SerializeField]
    private Sprite m_StopSprite; // 停止状态的图标

    [SerializeField]
    private bool m_IsPlaying = false; // 当前是否正在播放

    private Image m_CachedImage; // 缓存的 Image 组件

    public void DoPlay(bool value)
    {
        if (m_CachedImage == null)
        {
            m_CachedImage = GetComponent<Image>();
            if (m_CachedImage == null)
            {
                XKLog.LogError("Missing Image component on this GameObject.");
                return;
            }
        }

        if (m_PlaySprite == null || m_StopSprite == null)
        {
            XKLog.LogError("Sprites for play and stop states are not assigned.");
            return;
        }

        m_IsPlaying = value;
        m_CachedImage.sprite = m_IsPlaying ? m_PlaySprite : m_StopSprite;
    }

    private void Awake()
    {
        m_RotateAngle = -180; // 初始化旋转角度
        m_IsPlaying = false;
        m_CachedImage = GetComponent<Image>(); // 缓存 Image 组件
        if (m_CachedImage == null)
        {
            XKLog.LogError("Missing Image component on this GameObject.");
        }
    }

    private void Update()
    {
        if (Mathf.Approximately(m_RotateSpeed, 0f))
        {
            XKLog.LogWarning("Rotate speed is zero, no rotation will occur.");
            return;
        }

        // 更新旋转角度
        m_RotateAngle += m_RotateSpeed * Time.deltaTime;

        if (m_IsPlaying)
        {
            // 播放状态下，限制角度范围
            transform.Rotate(0f, 0f, m_RotateSpeed * Time.deltaTime);
            if (m_RotateAngle < -180)
            {
                m_RotateAngle = 0;
            }
        }
        else
        {
            // 停止状态下，逐渐回到初始角度
            if (m_RotateAngle > -180)
            {
                transform.Rotate(0f, 0f, -Mathf.Abs(m_RotateSpeed) * Time.deltaTime);
                m_RotateAngle = Mathf.Min(m_RotateAngle, -180);
            }
        }
    }
}